package com.woniuxy.portal.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.woniuxy.portal.common.Result;
import com.woniuxy.portal.common.constant.RedisConstant;
import com.woniuxy.portal.common.enums.impl.BusinessCode;
import com.woniuxy.portal.config.anon.Idempotent;
import com.woniuxy.portal.model.vo.CardVo;
import com.woniuxy.portal.model.vo.OrderVo;
import com.woniuxy.portal.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 提交订单
    @PostMapping("/submitOrder/{addressId}/{orderNum}")
    @Idempotent(expireTime = 30, timeunit = TimeUnit.SECONDS)
    public Result submitOrder(
            @PathVariable("addressId") Integer addressId,
            @PathVariable("orderNum") String orderNum,
            @RequestBody CardVo cardVo,@RequestHeader("Authorization") String token) {

        // 完成生成订单的幂等检查
        //String key = RedisConstant.ORDER_IDEMPOTENT_PREFIX + orderNum;
        //if (redisTemplate.hasKey(key)) {
        //    return Result.fail(BusinessCode.ORDER_REPEAT_SUBMIT);
        //}
        //// 首页提交（非重复提交），把key保存到redis中，实现接口幂等保证
        //redisTemplate.opsForValue().set(key,1, Duration.ofSeconds(30));

        // 从token中获取用户id
        token = token.replace("Bearer ", "");
        JWT jwt = JWTUtil.parseToken(token);
        Number userId = (Number) jwt.getPayload("userId");
        // 创建订单
        orderService.submitOrder(userId.intValue(),addressId,cardVo,orderNum);
        return Result.ok();
    }

    @GetMapping("/waitPay")
    public Result queryWaitPayOrder(@RequestHeader("Authorization") String token){
        token = token.replace("Bearer ", "");
        JWT jwt = JWTUtil.parseToken(token);
        Number nwf = (Number) jwt.getPayload("userId");
        Integer userId = nwf.intValue();
        //查询待支付的订单
        List<OrderVo> datas =  orderService.queryWaitPayOrder(userId);
        return Result.ok(datas);
    }

    // 点击去支付
    @PostMapping("/pay/{orderId}")
    @Idempotent(expireTime = 30,timeunit = TimeUnit.SECONDS)
    public Result payOrder(@PathVariable("orderId")Long orderId) {
        orderService.payOrder(orderId);
        return Result.ok();
    }
}



















